<?php
namespace app\admin\controller;

\think\Loader::import('controller/Controller', \think\Config::get('traits_path') , EXT);

use app\admin\Controller;
use think\Loader;
use think\Session;
use think\Db;
use think\exception\HttpException;
use think\Config;

class BranchList extends Controller
{
    use \app\admin\traits\controller\Controller;
    // 方法黑名单
    protected static $blacklist = [];

    public function index()
    {
        $model = $this->getModel();

        // 列表过滤器，生成查询Map对象
        $map = $this->search($model, [$this->fieldIsDelete => $this::$isdelete]);

        // 特殊过滤器，后缀是方法名的
        $actionFilter = 'filter' . $this->request->action();
        if (method_exists($this, $actionFilter)) {
            $this->$actionFilter($map);
        }

        // 自定义过滤器
        if (method_exists($this, 'filter')) {
            $this->filter($map);
        }

        $this->mydatalist($model, $map);

        return $this->view->fetch();
    }

    public function mydatalist($model, $map, $field = null, $sortBy = '', $asc = false, $return = false, $paginate = true)
    {
        // 私有字段，指定特殊条件，查询时要删除
        $protectField = ['_table', '_relation', '_field', '_order_by', '_paginate', '_model', '_func'];

        // 通过过滤器指定模型
        if (isset($map['_model'])) {
            $model = $map['_model'];
        }

        if (isset($map['_func']) && ($map['_func'] instanceof \Closure)) {
            call_user_func_array($map['_func'], [$model]);
        }

        // 排序字段 默认为主键名
        $order = $this->request->param('_order') ?: (empty($sortBy) ? $model->getPk() : $sortBy);

        // 接受 sort参数 0 表示倒序 非0都 表示正序
        $sort = null !== $this->request->param('_sort')
            ? ($this->request->param('_sort') == 'asc' ? 'asc' : 'desc')
            : ($asc ? 'asc' : 'desc');

        // 设置关联预载入
        if (isset($map['_relation'])) {
            $model = $model::with($map['_relation']);
        }

        // 设置字段
        if (isset($map['_field'])) {
            $field = $map['_field'];
        }

        // 设置有$map['_controller']表示存在关联模型
        if (isset($map['_table'])) {
            // 给排序字段强制加上表名前缀
            if (strpos($order, ".") === false) {
                $order = $map['_table'] . "." . $order;
            }
            // 给字段强制加上表名前缀
            $_field = is_array($field) ? $field : explode(",", $field);
            foreach ($_field as &$v) {
                if (strpos($v, ".") === false) {
                    $v = preg_replace("/([^\s\(\)]*[a-z0-9\*])/", $map['_table'] . '.$1', $v, 1);
                }
            }
            $field = implode(",", $_field);
            // 给查询条件强制加上表名前缀
            foreach ($map as $k => $v) {
                if (!in_array($k, $protectField) && strpos($k, ".") === false) {
                    $map[$map['_table'] . '.' . $k] = $v;
                    unset($map[$k]);
                }
            }
        }

        // 设置排序字段 防止表无主键报错
        $order_by = $order ? "{$order} {$sort}" : false;
        if (isset($map['_order_by'])) {
            $order_by = $map['_order_by'];
        }

        // 是否开启分页
        $paginate = isset($map['_paginate']) ? boolval($map['_paginate']) : $paginate;

        // 删除设置属性的字段
        foreach ($protectField as $v) {
            unset($map[$v]);
        }

        if ($paginate) {
            // 分页查询

            // 每页数据数量
            $listRows = $this->request->param('numPerPage') ?: Config::get("paginate.list_rows");

            $list = $model
                ->field($field)
                ->where($map)
                ->order($order_by)
                ->paginate($listRows, false, ['query' => $this->request->get()]);

            if ($return) {
                // 返回值
                return $list;
            } else {

                // 模板赋值显示

                $newlist = array();

                foreach($list as $w){

                    $ViewBusinessList = array();

                    $json = json_decode(htmlspecialchars_decode($w['business']) ,true);

                    foreach($json['content'] as $obj){

                        Array_push($ViewBusinessList, $obj['name']);

                    }

                    $new= implode(' | ',$ViewBusinessList);
                    $w['ViewBusiness'] = $new;

                    Array_push($newlist,$w );
                }

                $this->view->assign('list', $newlist);
                $this->view->assign("count", $list->total());
                $this->view->assign("page", $list->render());
                $this->view->assign('numPerPage', $list->listRows());
            }
        } else {
            // 不开启分页查询
            $list = $model
                ->field($field)
                ->where($map)
                ->order($order_by)
                ->select();

            if ($return) {

                // 返回值
                return $list;
            } else {
                // 模板赋值显示

                $this->view->assign('list', $list);
                $this->view->assign("count", count($list));
                $this->view->assign("page", '');
                $this->view->assign('numPerPage', 0);
            }
        }
    }

    public function add()
    {
        $controller = $this->request->controller();

        $groups = Db::name("business_list")->where(['status' => "1",'isdelete' => "0"])->order("id asc")->field('name,id,code')->select();

        //print_r($groups); die;

        $this->view->assign('groups', $groups);

        if ($this->request->isAjax()) {

            // 插入
            $data = $this->request->except(['id']);

            // 验证
            if (class_exists($validateClass = Loader::parseClass(Config::get('app.validate_path'), 'validate', $controller))) {

                $validate = new $validateClass();
                if (!$validate->check($data)) {
                    return ajax_return_adv_error($validate->getError());
                }
            }

            // 写入数据
            if (
                class_exists($modelClass = Loader::parseClass(Config::get('app.model_path'), 'model', $this->parseCamelCase($controller)))
                || class_exists($modelClass = Loader::parseClass(Config::get('app.model_path'), 'model', $controller))
            ) {
                //使用模型写入，可以在模型中定义更高级的操作
                $model = new $modelClass();

                $ret = $model->isUpdate(false)->save($data);

                $business =$data['business'];

                $newbusiness =json_decode(htmlspecialchars_decode($business),true) ;

                $content = $newbusiness['content'];

                $BranchId = Db::name('branch_list')->getLastInsID();

                if($ret == 1){

                    foreach($content as $value){

                        foreach($groups as $gro){

                            if($gro['name'] == $value['name']){



                                Db::name('branch_business')->insert(array('bisid'=>$gro['id'], 'branchid'=>$BranchId));

                            }
                        }
                    }
                }

            } else {
                // 简单的直接使用db写入
                Db::startTrans();

                try {
                    $model = Db::name($this->parseTable($controller));
                    $ret = $model->insert($data);
                    // 提交事务
                    Db::commit();

                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();

                    return ajax_return_adv_error($e->getMessage());
                }
            }

            return ajax_return_adv('添加成功');

        } else {
            // 添加
            return $this->view->fetch(isset($this->template) ? $this->template : 'edit');
        }
    }

    /**
     * 编辑
     * @return mixed
     */
    public function edit()
    {
        $controller = $this->request->controller();

        $groups = Db::name("business_list")->where(['status' => "1",'isdelete' => "0"])->order("id asc")->field('name,id,code')->select();

        $this->view->assign('groups', $groups);

        if ($this->request->isAjax()) {
            // 更新
            $data = $this->request->post();
            if (!$data['id']) {
                return ajax_return_adv_error("缺少参数ID");
            }

            // 验证
            if (class_exists($validateClass = Loader::parseClass(Config::get('app.validate_path'), 'validate', $controller))) {
                $validate = new $validateClass();
                if (!$validate->check($data)) {
                    return ajax_return_adv_error($validate->getError());
                }
            }

            // 更新数据
            if (
                class_exists($modelClass = Loader::parseClass(Config::get('app.model_path'), 'model', $this->parseCamelCase($controller)))
                || class_exists($modelClass = Loader::parseClass(Config::get('app.model_path'), 'model', $controller))
            ) {
                // 使用模型更新，可以在模型中定义更高级的操作
                $model = new $modelClass();

                $ret = $model->isUpdate(true)->save($data, ['id' => $data['id']]);

                $business =$data['business'];

                $newbusiness =json_decode(htmlspecialchars_decode($business),true) ;

                $content = $newbusiness['content'];

                $times = $data['times'];

                $branchid = $data['id'];

                $newtimes =json_decode(htmlspecialchars_decode($times),true) ;




                if($ret == 1){

                    $wechatAuth = new \WechatAuth(Config::get('weixin.appId'), Config::get('weixin.appSecret'));

                    $wechatAuth->getAccessToken();

                    $ordergroups = Db::name("queue_order")->where(['status' => "1",'branchid' => $branchid])->order("queue_time asc")->field('uid,queue_time,bisname,id')->select();

                    foreach($ordergroups as $gro){

                        if(in_array(date('Y-m-d', $gro['queue_time']),$newtimes)){

                            Db::name("queue_order")->where('id', $gro['id'])->update(array('status'=>'2'));

                            $openid = model('Member')->where(['uid' => $gro['uid']])->value('openid');

                            $data1 = array(
                                'first' => array('value' => "对不起,您的预约已取消", 'color' => "#00CD00"),
                                'keyword1' => array('value' => $gro['bisname'], 'color' => '#EE5C42'),
                                'keyword2' => array('value' => date('Y-m-d', $gro['queue_time']), 'color' => '#030303'),
                                'keyword3' => array('value' => '由于系统原因您预约的时间不能提供服务', 'color' => '#030303'),
                                'remark' => array('value' => '欢迎再次使用我们的服务', 'color' => '#030303'),
                            );
                            $result = $wechatAuth->doSendTpl($openid, 'NAXS7QUctxshBx0kVy6fAV5gC6Ykk7chsIVDG3zl-MU', 'http://bhgt.jslcwy.com', $data1);
                            file_put_contents('./4.txt', date('Y-m-d H:i:s') . ' ：' . json_encode($result) . PHP_EOL, FILE_APPEND);
                        }
                    }


                    foreach($groups as $gro){

                        $ret1 = Db::name('branch_business')->delete(array('branchid'=>$data['id'],'bisid'=>$gro['id']));
                    }

                    if($ret1 = 1){

                        foreach($content as $value){

                            foreach($groups as $gro){

                                if($gro['name'] == $value['name']){


                                    Db::name('branch_business')->insert(array('bisid'=>$gro['id'], 'branchid'=>$data['id']));

                                }
                            }
                        }



                    }
                }

            } else {
                // 简单的直接使用db更新
                Db::startTrans();
                try {
                    $model = Db::name($this->parseTable($controller));
                    $ret = $model->where('id', $data['id'])->update($data);

                    // 提交事务
                    Db::commit();
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    return ajax_return_adv_error($e->getMessage());
                }
            }

            return ajax_return_adv("编辑成功");
        } else {
            // 编辑
            $id = $this->request->param('id');
            if (!$id) {
                throw new HttpException(404, "缺少参数ID");
            }
            $vo = $this->getModel($controller)->find($id);
            if (!$vo) {
                throw new HttpException(404, '该记录不存在');
            }



            $json = json_decode(htmlspecialchars_decode($vo['times']) ,true);

            is_array($json)?null:$json = array();

            foreach($json as $obj){

                $zero1=date("y-m-d");
                $zero2= $obj;
                if(strtotime($zero1)> strtotime($zero2)){

                    $key=array_search($obj ,$json);

                    array_splice($json,$key,1);

                }
            }

            $vo['times'] = htmlentities(json_encode($json));


            $this->view->assign("vo", $vo);


            return $this->view->fetch();
        }
    }
    /**
     * 日期操作
     */
    public function forbid()
    {



        return $this->updateField($this->fieldStatus, 0, "禁用成功");
    }


}